<template>
  <div id="goods" v-if="goods && seller">
    <!-- 通过ref属性可以在Vue实例当中获取这个dom,挂载在父组件上面,可以通过$refs获取这个dom -->
    <div class="menu-wrapper" ref="menuWrapper" >
      <div>
        <div v-for="(item, index) in goods" :key="index" class="menu-item" @click="selectIndex(index, $event)" :class="{current: currentIndex === index}">
          <div class="text-wrapper border-1px">
            <span class="icon" v-show="item.type > 0" :class="classMap[item.type]"></span>
            <span class="text">{{item.name}}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="foods-wrapper" ref="foodsWrapper">
      <ul>
        <li v-for="(items, index) in goods" :key="index" class="foods-list-hook">
          <div class="items-title">{{ items.name }}</div>
          <ul>
            <li v-for="(item2, index) in items.foods" :key="index" class="items-content-wrapper" @click="changeShowGood" v-on:click="setGoodName(item2.name)">
              <div class="items-icon">
                <img :src="item2.icon" alt="">
              </div>
              <div class="items-content border-1px">
                <div class="items-name">{{item2.name}}</div>
                <div v-show="item2.description" class="items-description">{{item2.description}}</div>
                <div class="ratings">
                  <span>月售{{item2.sellCount}}份</span>
                  <span style="margin-left:12px;">好评率{{item2.rating}}%</span>
                </div>
                <div class="prices">
                  <span class="price">￥{{item2.price}}</span>
                  <span style="margin-left:12px;" class="oldPrice" v-if="item2.oldPrice">￥{{item2.oldPrice}}</span>
                </div>
                <div class="cart-control-wrapper">  
                  <cartControl :food="item2"></cartControl>
                </div>
              </div>
            </li>
          </ul>
        </li>
      </ul>
    </div>
    <!-- 购物车组件, 数据有app -》 goods -》 shopcart -->
    <shopcart :selectFoods="selectFoods" :deliveryPrice="seller.deliveryPrice" :minPrice="seller.minPrice"></shopcart>
  </div>
</template>

<script>
/**
 * goods页面也要请求的
 */
import axios from "axios";
import Vue from "vue";
import BScroll from "better-scroll";
import shopcart from "./shopcart";
import cartControl from "./cartControl";
import {mapState} from "vuex";
import {mapMutations} from "vuex";

/**
 * goods和cart-controls之间的数据传递并没有(父组件到子组件之间的数据传递), 而是父组件将数据通过props属性
 * 传递到子组件, 子组件向数据当中添加属性,这样就达到了数据的(共享和传递),在父组件当中同样能够访问到子组件,添加
 * 的数据
 */
export default {

  name: "goods",
  props: {
    seller: {
      type: Object
    },
    goods: {
      type: Array
    }
  },
  components: {
    shopcart,
    cartControl
  },
  data() {
    return {
      // goods: [],
      classMap: ["decrease", "discount", "special", "invoice-1", "guarantee"],
      heightList: [],
      scrollY: 0,
      mapState: [],
      showGoodItem: this.$store.state.showGoodItem
    };
  },
  methods: {
    // 通过点击来获取实时的index，然后让foodsScroll滚动到heightList[index]的高度,这样实现两个滑动的联动
    selectIndex($index, $event) {
      if (!$event._constructed) {
        return;
      }
      console.log($index, $event);
      let foodList = this.$refs.foodsWrapper.getElementsByClassName(
        "foods-list-hook"
      );
      this.foodsScroll.scrollToElement(foodList[$index], 300);
    },
    // 使用better-scroll来实现初始化
    _initscroll() {
      // 使用better-scroll的将这两部分封装两个滚动对象
      this.menuScroll = new BScroll(this.$refs.menuWrapper, {
        click: true
      });
      this.foodsScroll = new BScroll(this.$refs.foodsWrapper, {
        click: true,
        probeType: 3
      });
      // 为foodsScroll绑定scroll事件, 并实时获取此时foodsScroll的位置
      this.foodsScroll.on("scroll", pos => {
        this.scrollY = Math.abs(Math.round(pos.y));
      });
    },
    // 作用是将所有的foods-list-hook的高度放在一个数组当中保存起来
    _caculateHeight() {
      let foodList = this.$refs.foodsWrapper.getElementsByClassName(
        "foods-list-hook"
      );
      let height = 0;
      // 将热销榜这样块的高度，装进要给数组当中
      this.heightList.push(height);
      for (let i = 0; i < foodList.length; i++) {
        let item = foodList[i];
        height += item.clientHeight;
        this.heightList.push(height);
      }
    },
    setGoodName(goodName) {
      this.$emit('changeGoodName', goodName);
    },
    ...mapMutations({
      changeShowGood: 'changeShowGood',
      setSelectFood: 'setSelectFood'
    })
  },
  computed: {
    ...mapState({
      selectFood: "selectFood",
    }),
    // 这个计算属性，用来和实时的index判断，用来实现样式的切换
    currentIndex() {
      for (let i = 0; i < this.heightList.length; i++) {
        let height1 = this.heightList[i];
        let height2 = this.heightList[i + 1];
        if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) {
          return i;
        }
      }
      return 0;
    },
    selectFoods() {
      let foods = []; // 用来添加进来的事物,只要controls当中的数据变化就会执行这个计算属性
      if (this.goods.length !== 0) {
        this.goods.forEach(good => {
          good.foods.forEach(food => {
            if (food.count) {
              // 返回的拷贝goods下面的foods传入到shopcart当中，将goods当中每一个food都拷贝一份(一直在执行)
              foods.push(food);
            }
          });
        });
      }
      this.setSelectFood(foods);      // 将数据添加到vuex当中，可以在其他的组件当中共享
      return foods;                   // 存放这添加到购物车当中的foods数据
    },
  },
  created() {
    if(this.goods && this.seller) {
      Vue.nextTick(() => {
        this._initscroll();       // dom 绑定scroll
        this._caculateHeight();   // 计算高度的函数
      });
    }
  }
};
</script>

<style lang="stylus" ref="stylesheet/stylus">
@import '../assets/stylus/index.styl';

#goods {
  display: flex;
  position: absolute;
  top: 172px;
  bottom: 48px;
  left: 0;
  right: 0;
  width: 100%;
  overflow: hidden;

  .icon {
    display: inline-block;
    vertical-align: top;
    width: 14px;
    height: 14px;
    background-size: 14px 14px;

    &.decrease {
      bg-image('decrease_3');
    }

    &.discount {
      bg-image('discount_3');
    }

    &.guarantee {
      bg-image('guarantee_3');
    }

    &.invoice {
      bg-image('invoice_3');
    }

    &.special {
      bg-image('special_3');
    }
  }

  .menu-wrapper {
    flex: 0 0 80px;
    width: 80px;
    background-color: #f3f5f7;

    .menu-item {
      padding: 0 12px;
      font-size: 0;
      line-height: 16px;

      &.current {
        position: relative;
        margin-top: -1px;
        background-color: #ffffff;

        &:after {
          border-top: 1px solid #ffffff;
        }

        .text {
          font-size: 12px;
          line-height: 12px;
          font-weight: 500;
        }
      }

      .text {
        font-size: 12px;
        line-height: 14px;
        font-weight: 200;
      }

      .text-wrapper {
        // 让每一个格子的高度固定
        display: table-cell;
        vertical-align: middle;
        height: 54px;
        width: 56px;
        border-1px(rgba(7, 17, 27, 0.1));
      }
    }
  }

  .foods-wrapper {
    flex: 1;
    background-color: #ffffff;

    .items-title {
      height: 26px;
      font-size: 12px;
      padding-left: 14px;
      color: rgb(147, 153, 159);
      line-height: 26px;
      background-color: #f3f5f7;
      border-left: 4px solid #d9dde1;
    }

    .items-content-wrapper {
      display: flex;
      // 用margin保证下面的border不是抵着边的
      margin: 18px;
      padding-bottom: 18px;
      position: relative;
      background-color: #ffffff;
      border-1px(rgba(7, 17, 27, 0.1));

      &:last-child {
        border-1px(rgb(255, 255, 255));
        margin-bottom: 0;
      }

      .items-icon {
        flex: 0 0 57px;

        img {
          height: 57px;
          width: 57px;
        }
      }

      .items-content {
        flex: 1;
        padding-left: 10px;

        .items-name {
          font-size: 14px;
          color: rgb(7, 17, 27);
          line-height: 14px;
          margin-top: 2px;
        }

        .items-description, .ratings {
          margin-top: 8px;
          font-size: 10px;
          color: rgb(147, 153, 159);
          line-height: 16px;
        }

        .ratings {
          span {
            display: inline-block;
          }
        }

        .price {
          font-size: 20px;
          color: rgb(240, 20, 20);
          font-weight: 700;
          line-height: 24px;
        }

        .oldPrice {
          font-size: 10px;
          vertical-align: top;
          color: rgb(147, 153, 159);
          font-weight: 700;
          line-height: 20px;
          text-decoration: line-through;
        }

        .cart-control-wrapper {
          position: absolute;
          right: 0;
          bottom: 12px;
        }
      }
    }
  }
}
</style>

